package com.levi.distributedlock.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/zk")
public class ZookeeperController {

    @Value("${zookeeper.lockpath}")
    private String lockpath;

    @Value("${zookeeper.address}")
    private String address;



    @GetMapping("/secKill")
    public void secKill() throws Exception {
        RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(address, 60000, 15000, retry);
        curatorFramework.start();
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockpath);
        //等待2秒
        if (lock.acquire(2, TimeUnit.SECONDS)) {
            log.info("{}获得了锁",Thread.currentThread().getName());
            Thread.sleep(1000);
            lock.release();
        }else{
            log.info("{}没有获得锁",Thread.currentThread().getName());
        }
//-----------------------------------------

    }

    public static void main(String[] args) {
        StringBuilder adv = new StringBuilder("adv");
        StringBuffer ddd = new StringBuffer("ddd");
        HashSet<String> set = new HashSet<>();
        set.add("1");
        set.add("2");
        set.add("3");
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    }
}
